<?php

class Home_Controller extends Base_Controller {

    public $restful = true;
    public $_data = array();

    public function get_index() {
        $cl = new CategoryLogic();
        //$catList = $cl->getSchedulePageCatlist();
        //$catList = $cl->listCategoryTree();
        $video_list = $cl->getHomepageProductList();
        $news = new News();
        $news_info = $news->listNews(1);
        //dd($news_info);
        //dd($catList);
        return View::make('home.index')->with("video_list", $video_list)->with("news", $news_info->results);
    }

    public function get_reviews() {
        $video_id = Input::get('id');
        $rl = new ReviewLogic();
        //每页5个
        $ret = $rl->getReviewByVideoID($video_id, 3);
        return Response::json(array("results" => $ret->results, "links" => $ret->appends(array('id' => $video_id))->links()));
    }

    public function get_course() {
        //面包屑, 亦为array
        //TODO 拿到video的$catID $videoID
        $videoID = Input::get('id');
        if (empty($videoID))
            $videoID = 7;
        $catID = Input::get('category_id');
        if (empty($catID))
            $catID = 0;
        $catLogic = new CategoryLogic();
        $bc = $catLogic->getHieraCats($catID);
        unset($catLogic);
        $videoLogic = new VideoLogic();
        $videoInfo = $videoLogic->getVideoInfoByID($videoID);
        unset($videoLogic);
        $rl = new ReviewLogic();
        $average_score = $rl->getAverageScoreByVideoID($videoID);
        return View::make('home.course')->with("bc", $bc)->with("videoInfo", $videoInfo)->with("score", $average_score)->with("video_id", $videoID);
    }

    public function post_review() {
        if (!Input::has('video_id') || !Input::has('text')) {
            return Response::json(array("state" => False));
        }
        $video_id = Input::get('video_id');
        $user_id = Input::get('user_id', intval(session::get('user_id')));
        $author = Input::get('author', session::get('username'));
        if (empty($user_id) || empty($author)) {
            return Response::json(array("state" => False));
        }
        $text = Input::get('text');
        $rating = Input::all('rating', 50);
        $reviewModel = new ReviewLogic();
        $ret = $reviewModel->insertReview($video_id, $user_id, $author, $text, $rating);
        unset($reviewModel);
        if ($ret) {
            return Response::json(array("state" => true));
        } else {
            return Response::json(array("state" => false));
        }
    }

    public function get_video() {
        if (!Input::has('id') || !Input::has('uuid')) {
            return Response::json(array("state" => false));
        }

        $tokenServiceURL = 'http://' . UMSConfig::IP . ':' . UMSConfig::TOKEN_PORT . '/gettoken?token=' . UMSConfig::TOKEN . '&app=vod&limit=2&duration=600';
        $token = file_get_contents($tokenServiceURL);

        $videoID = intval(Input::get('id'));
        $videoLogic = new VideoLogic();
        $title = $videoLogic->getTitleByID($videoID);
        unset($videoLogic);
        $uuid = Input::get('uuid');
        $videoURL = 'rtmp://' . UMSConfig::IP . ':' . UMSConfig::VIDEO_PORT . '/vod?token=' . $token;
        $para = array(
            'title' => $title,
            'uuid' => $uuid,
            'videoURL' => $videoURL,
        );
        return View::make('home.video')->with('para', $para);
    }

    public function get_schedule() {

        $catID = Input::get('category_id');
        if (empty($catID))
            $catID = 0;

        $catLogic = new CategoryLogic();
        $catList = $catLogic->getSchedulePageCatlist();
        unset($catLogic);
        $videoLogic = new VideoLogic();
        //TODO catID赋值
        //getVideolistByCatID($category_id, $per_page) 
        //$catID=9;
        $video_list = $videoLogic->getVideolistByCatID($catID, 40);
        //dd($video_list);
        //dd($catList);
        $catLogic = new CategoryLogic();
        $bc = $catLogic->getHieraCats($catID);
        //dd($bc);
        //dd($video_list);
        return View::make('home.schedule')->with("bc", $bc)->with("catList", $catList)->with("video_list", $video_list);
    }

    public function get_search() {
        $search_word = Input::get('wd');
        $data = array();
        if (empty($search_word)) {
            return $data;
        }
        $catID = null;
        if (Input::has('category_id')) {
            $catID = intval(Input::get('category_id'));
        }
        $videoLogic = new VideoLogic();
        /* data 格式: array(catArray,productArray), 该array均无string key, catarray格式为array(id, name, count), productArray为, 其中desc_abstract
         * 为描述摘要, 30个字符
         * {
          title: "cpp编程",
          duration: "100",
          image: "/upload/MTM2NjU0Mjk4MA==.jpg",
          price: "1000000000",
          type: "0",
          viewed: "0",
          status: "1",
          ctime: "2013-04-06 18:43:03",
          sort_order: "0",
          category_id: "15",
          category_name: "我们",
          desc_abstract: "edwinxie的第一个教程edwinxie的第一个教程ed"
          },
         */
        $data = $videoLogic->getSearchData($search_word, $catID);

        //dd($data);
        return View::make('home.search')->with('data', $data)->with('wd', $search_word);
        ;
    }

    public function get_login() {

        if (Auth::check()) {
            return Redirect::to("/");
        }

        $name = Cookie::get('username');
        $password = Cookie::get('password');
        $credentials = array('username' => $name, 'password' => $password);
        if (Auth::attempt($credentials)) {
            $user = new Users();
            $user_info = $user->getUserId($name);
            $user_id = $user_info[0]->id;
            Session::put('username', Input::get('username'));
            //Session::put('user_id', Input::get('user_id'));
            Session::put('user_id', $user_id);
            return Redirect::to("/");
        }
        return View::make('home.login')->with("user_info", array("username" => ""));
    }

    public function get_logout() {
        //$name = Cookie::get('username');
        //$password = Cookie::get('password');
        //$credentials = array('username' => $name, 'password' => $password);
        //if (Auth::attempt($credentials)) {
        Session::forget('username');
        Cookie::forget('username');
        Cookie::forget('password');
        Auth::logout();
        //}
        return Redirect::to("/");
    }

    public function post_login() {
        $this->_data['input'] = Input::get();
        $name = Input::get('username') ? Input::get('username') : Cookie::get('username');
        $password = Input::get('password') ? Input::get('password') : Cookie::get('password');
        $credentials = array('username' => $name, 'password' => $password);

        /* $rules = array(
          'captcha' => 'laracaptcha|required'
          );
          $validation = Validator::make(Input::all(), $rules);

          if (!$validation->valid())
          {
          echo Response::json(array("state"=>false,'message'=>'用户验证码错误'));
          return;
          } */


        if (Auth::attempt($credentials)) {
            $user = new Users();
            $user_info = $user->getUserId($name);
            $user_id = $user_info[0]->id;
            Session::put('username', Input::get('username'));
            Session::put('user_id', $user_id);
            if (Input::get("remember") == '1') {
                Cookie::put('username', $name);
                Cookie::put('password', $password);
            }
            return Redirect::to("/");
        }

        return View::make('home.login')->with("user_info", array("username" => $name));
        //view
    }

    public function get_register() {

        return View::make('home.register');
    }

    public function post_register() {
        $err_msg = "";
        $rules = array(
            'captcha' => 'laracaptcha|required'
        );
        $validation = Validator::make(Input::all(), $rules);

        if (!$validation->valid()) {
            $err_msg = "验证码错误";
            return View::make('home.register')->with("err_msg", $err_msg);
        }

        $password = Input::get('password');
        $confirm = Input::get('confirm');
        if ($password !== $confirm) {
            $err_msg = "两次密码不一致";
            $this->_data["state"] = false;
            return View::make('home.register')->with("err_msg", $err_msg);
            return;
        }

        $this->model_users = new Users();
        $input = Input::get();
        unset($input['confirm']);
        unset($input['captcha']);
        $input['password'] = Hash::make($input['password']);
        $this->_data["state"] = $this->model_users->addUsers($input);
        //dd($this->_data["state"]);
        return View::make('home.register');
    }

}

